package com.weavernorth.hlymess;


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpEntity;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import weaver.general.BaseBean;
import weaver.general.Util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 公共工具类
 *
 * @author zm
 * @version V1.0 2019-12-03 created
 */
public class CommonUtil {
    public static Log log = LogFactory.getLog(CommonUtil.class.getName());

    /**
     * 发送post请求,汇联易获取token值
     *
     * @param strUrl      路径
     * @param strEncoding 编码格式
     * @return
     * @throws IOException
     */
    public static String sendPost(String strUrl, String strEncoding) throws IOException {
        //基础类
        BaseBean bb = new BaseBean();
        //返回值
        String strBody = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(strUrl);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        //装填参数,form-data里传参
        Map<String, Object> params = new HashMap();
        //此参数值为汇联易提供
        params.put("grant_type", "client_credentials");
        params.put("scope", "write");

        //用户名:fbb0333d-11ea-4c12-93cb-46f06dbe440c 密码: OTg3ZWFjMDctZGQ4NC00YTcxLThlZDYtNTlhNzZjZmZkZmVh
        //Authorization值为(用户名:密码)base64加密出来的
        String strAuthor = Util.null2String(bb.getPropValue("hlyMess", "authorization"));
        httpPost.setHeader("Authorization", "Basic " + strAuthor);
        ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            if (entry.getValue() == null) {
                continue;
            }
            // 类似浏览器表单提交，对应input的name和value
            builder.addTextBody(entry.getKey(), entry.getValue().toString(), contentType);
        }
        HttpEntity entity = builder.build();
        httpPost.setEntity(entity);
        try {
            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            // log.info("返回状态=="+response);
            //获取结果实体
            HttpEntity entitys = response.getEntity();
            if (entitys != null) {
                //按指定编码转换结果实体为String类型
                strBody = EntityUtils.toString(entitys, strEncoding);
            }
            EntityUtils.consume(entitys);
            //释放链接
            response.close();
        } catch (Exception e) {
            log.info("异常捕获=" + e);
        }

        return strBody;
    }


    /**
     * 发送post请求,汇联易获取待办数量
     *
     * @param strUrl       请求路径
     * @param jsonUser     请求体
     * @param strToken     请求token
     * @param strTokenType 请求token类型
     * @return
     * @throws IOException
     */
    public static String senDealPost(String strUrl, JSONObject jsonUser, String strToken, String strTokenType) throws IOException {
        String strBody = "";

        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(strUrl);
        //装填参数
        StringEntity stringEntity = new StringEntity(jsonUser.toString(), "utf-8");
        stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        //设置参数到请求对象中
        httpPost.setEntity(stringEntity);
        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/json");
        //Authorization 值为token_type和token值
        httpPost.setHeader("Authorization", strTokenType + strToken);
        try {
            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            // log.info("返回状态=="+response);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            Header[] headerArray = response.getHeaders("X-Total-Count");
            for (Header header : headerArray) {
                log.info("--Header-----------------------------------------");
                log.info("----Key: " + header.getName());
                log.info("----RawValue: " + header.getValue());
                strBody=header.getValue();

            }

//            if (entity != null) {
//                //按指定编码转换结果实体为String类型
//                strBody = EntityUtils.toString(entity, "utf-8");
//            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            log.info("异常捕获=" + e);
        }

        return strBody;
    }


    public static void main(String[] args) {
        CommonUtil commonUtil = new CommonUtil();


        try {
            String resultStr = sendPost("https://api.huilianyi.com/oauth/token", "utf-8");

            System.out.println(resultStr);
        } catch (IOException e) {
            e.printStackTrace();
        }


//{"status":1,"data":{"userId":"caohuixian","userName":"曹辉宪"},"rel":true}
//{"status":500,"message":"服务器开小差了"}http://gateway2.dacity.cn:8765/api/auth/jwt/verificationToken
//http://219.239.169.108:8080/weavernorth/dac/ssologin/jsp/sysAgent.jsp?token=eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiLmm7novonlrqoiLCJ1c2VySWQiOiI0ODI5MCIsIm5hbWUiOiJjYW9odWl4aWFuIiwiYXBwaWQiOiIxIiwiZXhwIjoxNTU5NzU3MzM2fQ.rGG3mSoGAOdBgauQrNVDeNw8NGcIZo_yOJvKuc2oeSZVc2EdNI7P4mn4PvtqQwMSHUMODuMMTKg_AwALNkX53OVHDVv19N5kn54JVgVhB9-tHDdpknGN4VsyheSX9gTLGHnz2ybF0cdqCvuzrFiXHaLyE6PE3d6olvgL-djcQlY
    }
}

